<!--********************************************************************
* Copyright© 2000 - 2025 SuperMap Software Co.Ltd. All rights reserved.
*********************************************************************-->
<!--********************************************************************
* 该示例需要引入
* snap (https://iclient.supermap.io/web/libs/mapbox-gl-draw-snap-mode/0.2.1/mapbox-gl-draw-snap-mode.min.js)
*********************************************************************-->
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title data-i18n="resources.title_editFeatures"></title>
    <script type="text/javascript" include="draw,snap,lodash" src="../../dist/mapboxgl/include-mapboxgl.js"></script>
    <style>
      .key-input,
      .value-input {
        display: inline-block;
        width: 100px;
        margin-right: 5px;
      }
      .edit-panel {
        position: absolute;
        top: 30px;
        right: 20px;
        width: 300px;
      }
      .btn-primary {
        padding: 4px 6px !important;
        background-color: #0081e2 !important;
         border-color: #0081e2 !important;
      }

      .btm-gray {
        padding: 4px 6px !important;
        background-color: #aaa !important;
         border-color: #aaa !important;
      }

      .button-group {
        background-color: #fff;
        /* height: 60px; */
        overflow: hidden;
        padding-top: 12px;
        padding-bottom: 12px;
        text-align: center;
      }

      .dataset-info {
        padding-left: 8px;
        font-size: 13px;
        font-weight: 100;
        color: #a09595;
      }

      .add-feature-info,
      .delete-feature-info,
      .edit-feature-info  {
        padding: 10px;
        max-height: 745px;
        overflow-y: scroll;
      }

      .btn-group-xs {
        margin-right: 6px;
      }

      .into-title {
        font-weight: 800;
        font-size: 16px;
      }
      .add-attribute-info,
      .edit-attribute-info {
        /* margin-bottom: 50px; */
      }

      .info-panel {
        margin-top: -14px
      }

      .info-panel > div {
        margin-top: 25px;
        width: 300px;
        min-height: 300px;
        background: #fff;
        display: none;
      }

      .delete-modal {
        position: absolute;
        top: -70px;
        right: 0px;
        width: 260px;
        background: #fff;
        border-radius: 10px;
        padding: 10px;
        display: none;
        border: 1px solid #a39a9a;
      }

      .select-element {
        width: 100%;
        height: 26px;
        border: 1px solid #a39a9a;
      }
      .line-element {
        width: 4px;
        display: inline-block;
        height: 16px;
        background: #0081e2;
        vertical-align: bottom;
        margin-right: 6px;
      }

      .video-element {
        width: 100%;
      }

      .video-modal {
        z-index: 9999;
        width: 100%;
        height: 100%;
        margin: 0 auto;
        display: none;
        position: absolute;
        justify-content: center;
        align-items: center;
        left: 0;
        top: 0;
        background: #0000008a;
      }

      .desc-element {
        font-size: 12px;
        margin-top: 10px;
      }

      .input-element {
        width: 100%;
        height: 26px;
        border: 1px solid #a39a9a;
      }

      #drawList {
        margin-bottom: 10px;
      }
      .info-bottom {
        position: absolute;
        right: 20px;
        margin-top: 40px;
        bottom: 10px;
      }
      .edit-tips {
        width: 300px;
        height: 25px;
        background: #fff;
        margin-top: 25px;
        padding: 3px 10px;
        display: none;
      }
      .img-element {
        margin-top: 10px;
        width: 90%;
      }

      dialog {
        width: 100%;
        max-width: 720px;
        display: none;
      }

      .playIcon{
        position: absolute;
        transform: translate(-50%, -50%);
        left: 50%;
        top: 58%;
        width: 36px;
        height: 36px;
        background: url('../img/play1.png') no-repeat;
        background-size: contain;
      }
      .video-element, .img-element, .playIcon{
        cursor: pointer;
      }
      .button-group, .info-panel, .edit-tips {
        box-shadow: 0px 0px 5px 0 rgba(0,0,0,0.3);
      }
      .add-tips {
        display: none;
        color: red;
        margin-right: 16px;
      }
      .message {
        height: 50px;
        position: absolute;
        top: 15px;
        font-size: 16px;
        left: 50%;
        padding: 15px;
        display: none;
        margin-left: -150px;
        background: #fff;
      }
    </style>
  </head>
  <body style="margin: 0; overflow: hidden; background: #fff; width: 100%; height: 100%; position: absolute; top: 0">
    <div id="map" style="width: 100%; height: 100%"></div>
    <div id="popup" class="ol-popup">
      <p><span data-i18n="resources.msg_inputCoordinates"></span></p>
      <div id="popup-content">
        <h5>X</h5>
        <input class="input-element coordX" type="number">
        <h5>Y</h5>
        <input class="input-element coordY" type="number">
      </div>
    </div>
    <div class="video-modal">
      <button class="video-modal-close">Close</button>
      <video controls width="720">
        <source src="" type="video/mp4">
      </video>
    </div>
    <div class="message">
      <span class="glyphicon glyphicon-exclamation-sign" style="color: #ec5812;"></span>
      <span><span data-i18n="resources.msg_pleaseSaveFirst"></span></span>
    </div>
    <div class="edit-panel">
      <div class="button-group">
        <button
          id="addFeature"
          value="Point"
          type="button"
          class="btn btn-primary btn-group-xs"
        >
          <span class="glyphicon glyphicon-plus" aria-hidden="true"><span data-i18n="resources.text_addFeature"></span></span>
        </button>
        <button
          id="editFeature"
          value="LineString"
          type="button"
          class="btn btn-primary btn-group-xs"
        >
          <span class="glyphicon glyphicon-edit" aria-hidden="true"><span data-i18n="resources.text_editFeature"></span></span>
        </button>
        <button
          id="deleteFeature"
          value="Polygon"
          type="button"
          class="btn btn-primary btn-group-xs"
        >
          <span class="glyphicon glyphicon-trash" aria-hidden="true"><span data-i18n="resources.text_deleteFeature"></span></span>
        </button>
      </div>
      <div class="info-panel">
        <div class="add-feature-info">
          <h4 class="into-title"><span data-i18n="resources.text_addFeature"></span></h4>
          <div>
            <h5><span data-i18n="resources.text_targetDataset"></span></h5>
            <select class="select-element addDatasetNameList" name="capital">
            </select>
          </div>
          <h6><span class="line-element"></span><span data-i18n="resources.text_spacialInfo"></span></h6>
          <div class="space-info">
            <input class="input-element" type="text" disabled>
            <p class="desc-element"><span data-i18n="resources.msg_moveToMapDraw"></span></p>
          </div>
          <h6><span class="line-element"></span><span data-i18n="resources.text_attributeInfo"></span></h6>
          <div class="add-attribute-info">
          </div>
          <div class="info-bottom">
            <p class="add-tips"><span data-i18n="resources.msg_pleaseSave"></span></p>
            <button class="btn btn-default btn-group-xs cancel-add" data-i18n="resources.btn_cancel"></button>
            <button class="btn btn-primary btn-group-xs addSave" data-i18n="resources.btn_save"></button>
          </div>
        </div>
        <div class="edit-feature-info">
          <h4 class="into-title"><span data-i18n="resources.text_editFeature"></span><span class="dataset-info"><span data-i18n="resources.text_dataset"></span>：<span class="edit-dataset"></span></span></h4>
          <h6><span data-i18n="resources.text_spacialInfo"></span></h6>
          <div class="space-info">
            <input class="input-element" type="text" disabled>
          </div>
          <h6><span data-i18n="resources.text_attributeInfo"></span></h6>
          <div class="edit-attribute-info">
          </div>
          <div class="info-bottom">
            <p class="add-tips"><span data-i18n="resources.msg_pleaseSave"></span></p>
            <button class="btn btn-default btn-group-xs cancel-edit" data-i18n="resources.btn_cancel"></button>
            <button disabled class="btn btn-primary btn-group-xs editSave" data-i18n="resources.btn_save"></button>
          </div>
        </div>
        <div class="delete-feature-info">
          <h4 class="into-title"><span data-i18n="resources.text_deleteFeature"></span></h4>
          <p class="desc-element"><span data-i18n="resources.msg_selectDeleteFeature"></span></p>
          <div style="border-top: 1px solid #baafaf">
            <h5><span data-i18n="resources.text_featureToDelete"></span>:</h5>
            <div class="delete-feature-list">

            </div>
          </div>
          <div class="info-bottom">
            <div class="delete-modal">
              <p><span data-i18n="resources.msg_confirmDelete"></span></p>
              <div class="btns">
                <button class="final-delete-cancel btn btn-default btn-group-xs" data-i18n="resources.btn_cancel"></button>
                <button class="final-delete btn btn-danger btn-group-xs"><span data-i18n="resources.text_input_value_delete"></span></button>
              </div>
            </div>
            <button class="btn btn-default btn-group-xs cancel-delete" data-i18n="resources.btn_cancel"></button>
            <button class="btn btn-danger btn-group-xs delete"><span data-i18n="resources.text_input_value_delete"></span></button>
          </div>
        </div>
      </div>
      <div class="edit-tips"><span data-i18n="resources.msg_clickToSelect"></span></div>
    </div>
    <script type="text/javascript" include="jquery,bootstrap,widgets.alert,viewer" src="../js/include-web.js"></script>
    <script type="text/javascript">
      var status = 'ADD';
      var type = '';
      var uniqueId = 0;
      var currentDataset = 'buildings_R';
      var map,
        draw,
        url = (window.isLocal ? window.server : "https://iserver.supermap.io") + "/iserver/services/map-china/rest/maps/China/zxyTileImage.png?z={z}&x={x}&y={y}";
      var isUpdate = false;
      var dataUrl = "https://iserver.supermap.io/iserver/services/data-building/rest/data";
      var dataSourceName = 'building';
      var editFeaturesService = new mapboxgl.supermap.FeatureService(dataUrl);
      var currentShowPanel = '';
      var datasetNameList = [];
      var datasetTypeClassify = {
        Fill: [],
        Line: [],
        Point: []
      }
      var deleteList = {};
      var currentFeature = {};
      var updateChanged = false;
      var addFeatureId = null;
      var curEditOriginFeatures = [];
      var typeMap = {
                REGION: 'Fill',
                LINE: 'Line',
                POINT: 'Point'
              };
      var domainRules = {
        
      };
      var datasetInfoList = {

      }
      var container = document.getElementById('popup');
      var content = document.getElementById('popup-content');
      var isChanged = false;
      var preSelectId = null;
      map = new mapboxgl.Map({
        container: 'map',
        style: {
            "version": 8,
            "sources": {
                "raster-tiles": {
                    "type": "raster",
                    "tiles": [url],
                    "tileSize": 256
                }
            },
            "layers": [{
                "id": "simple-tiles",
                "type": "raster",
                "source": "raster-tiles",
            }]
        },
        center: [116.435, 39.92],
        zoom: 16,
    });
      bindEvents();
      init(dataUrl, dataSourceName);

      function addVectorLayer(type, features, datasetName) {
        var typeMap = {
          Point: 'circle',
          LineString: 'line',
          MultiLineString: 'line',
          MultiPolygon: 'fill',
          Polygon: 'fill'
        }
        type = typeMap[type];
        var styleOptions = {
          circle: {
            'circle-color': '#e55561',
            'circle-radius': 8
          },
          line: {
            'line-color': '#3388ff',
            'line-width': 4
          },
          fill: {
            'fill-color': '#3388ff',
            'fill-opacity': 0.3
          }
        }
          map.addLayer({
            id: datasetName,
            type: type,
            source: {
              type: 'geojson',
              data: features
            }, 
            paint: styleOptions[type]
          });
      }
      var fieldList = [];
      var filterFields = {
      };

      function getDomains(datasetName) {
        var xhr = new XMLHttpRequest();
        xhr.open('GET', dataUrl + "/datasources/" + dataSourceName + "/datasets/" + datasetName + "/domain.json", true);
        xhr.onreadystatechange = function() {
          if (xhr.readyState === 4 && xhr.status === 200) {
            var res = JSON.parse(xhr.responseText);
            domainRules = {};
            res && Array.isArray(res) && res.forEach(function(domain) {
              var key = domain.fieldName.toUpperCase();
              domainRules[key] = domain;
            });
          }
        };
        xhr.send();
      }

      function checkInput(e) {
        if (!updateChanged && status === 'EDIT') {
          updateChanged = true;
          document.querySelector('.editSave').disabled = false;
        }
        var rule = domainRules[e.target.label];
        if (rule && rule.type === 'RANGE') {
          var value = +e.target.value;
          if (value < rule.rangeInfos[0].min || value > rule.rangeInfos[0].max) {
            e.target.style.borderColor = 'red';
            var parent = e.target.parentNode;
            var error = document.createElement('span');
            error.style.color = 'red';
            error.className = 'error-tips';
            error.innerText = resources.text_outOfRange +'：[' + rule.rangeInfos[0].min + ', ' + rule.rangeInfos[0].max + ')';
            parent.insertBefore(error, e.target.nextSibling);
            document.querySelector('.editSave').disabled = true;
            // 保存按钮 disabled
          } else {
            var error = document.querySelector('.error-tips');
            error && error.parentNode.removeChild(error);
            e.target.style.borderColor = '#000';
            document.querySelector('.editSave').disabled = false;
          }
        }

        if (e.target.parentNode.className === 'VIDEO') {
            deleteVideoAndImg(e);
            if(e.target.value) {
              var videoPlayIcon = document.createElement('div');
              videoPlayIcon.className = 'playIcon';
              var video = document.createElement('video');
              video.src = e.target.value;
              video.className = 'video-element ' + e.target.label;
              var parent = e.target.parentNode;
              parent.insertBefore(video,e.target.nextSibling);
              parent.insertBefore(videoPlayIcon,video);
              previewVideo(video);
            }
          } else if (e.target.parentNode.className === 'IMG') {
            deleteVideoAndImg(e);
            if(e.target.value) {
              var img = document.createElement('img');
              img.src = e.target.value;
              img.className = 'img-element ' + e.target.label;
              new Viewer(img);
              var parent = e.target.parentNode;
              parent.insertBefore(img,e.target.nextSibling);
            }
          }
      }

      function deleteVideoAndImg(e) { 
        var ele = document.querySelector('.' + e.target.label + ' img') || document.querySelector('.' + e.target.label + ' video');
        var videoPlayIcon = document.querySelector('.' + e.target.label + ' .playIcon');
        if (ele) {
          ele.parentNode.removeChild(ele);
        }
        if (videoPlayIcon) {
          videoPlayIcon.parentNode.removeChild(videoPlayIcon);
        }
      }

      getDomains(currentDataset);

      function init(dataUrl, datasourceName) {
        var styles = mapboxGlDrawSnapMode.SnapModeDrawStyles;
        styles.forEach(function(style) {
          if (['gl-draw-line-static', 'gl-draw-line-inactive', 'gl-draw-line-active'].indexOf(style.id) > -1) {
            style.paint['line-color'] = '#3388ff';
            style.paint['line-width'] = 3;
          }
          if (['gl-draw-point-static', 'gl-draw-point-inactive', 'gl-draw-point-active'].indexOf(style.id) > -1) {
            style.paint['circle-color'] = '#e55561';
            style.paint['circle-radius'] = 8;
          }
        if (['gl-draw-polygon-stroke-inactive', 'gl-draw-polygon-stroke-static', 'gl-draw-polygon-stroke-active'].indexOf(style.id) > -1) {
          style.paint['line-color'] = '#3388ff';
          style.paint['line-opacity'] = 0.3;
        }
          if (['gl-draw-polygon-fill-static', 'gl-draw-polygon-fill-inactive', 'gl-draw-polygon-fill-active'].indexOf(style.id) > -1) {
            style.paint['fill-color'] = '#3388ff';
            style.paint['fill-outline-color'] = '#3388ff';
            style.paint['fill-opacity'] = 0.3;
          }
        });
        var modes = {};
        for (var key in MapboxDraw.modes) {
          if (MapboxDraw.modes.hasOwnProperty(key)) {
            modes[key] = MapboxDraw.modes[key];
          }
        }
        modes.draw_point = mapboxGlDrawSnapMode.SnapPointMode;
        modes.draw_polygon = mapboxGlDrawSnapMode.SnapPolygonMode;
        modes.draw_line_string = mapboxGlDrawSnapMode.SnapLineMode;
        modes.direct_select = mapboxGlDrawSnapMode.SnapDirectSelect;
        draw = new MapboxDraw({
          modes: modes,
          styles: styles,
          userProperties: true,
          snap: true,
          displayControlsDefault: false,
          snapOptions: {
            snapPx: 15, // defaults to 15
            snapToMidPoints: true, // defaults to false
            snapVertexPriorityDistance: 0.0025, // defaults to 1.25
          },
          guides: false,
          defaultMode: 'simple_select'
        });
        map.addControl(draw, 'top-left');
        map.on('draw.create', function (e) {
          if (e.features) {
            var feature = e.features[0];
            addFeatureId = feature.id;
            datasetInfoList[currentDataset].id++;
            feature.id = datasetInfoList[currentDataset].id;
            currentFeature.data = feature;
            document.querySelector('.add-feature-info>.space-info>.input-element').value = JSON.stringify({ geometry: currentFeature.data.geometry});
            isChanged = true;
          }
        });
        var datasetService = new mapboxgl.supermap.DatasetService(dataUrl)
        datasetService.getDatasets(datasourceName, function(e) {
          datasetNameList = e.result.datasetNames;
          currentFeature.dataset = datasetNameList[0];
          currentDataset = datasetNameList[0];
          var count = 0;
          datasetNameList.forEach(function(datasetName, index) {
            filterFields[datasetName] = {};
            datasetService.getDataset(dataSourceName, datasetName, function(e) {
            datasetInfoList[datasetName] = {
              type: e.result.datasetInfo.type,
              id: 0
            }
            typeMap[e.result.datasetInfo.type] && datasetTypeClassify[typeMap[e.result.datasetInfo.type]].push(datasetName);
            count++;
            if (index === 0) {
              var editType = e.result.datasetInfo.type;
              createOptions(datasetNameList, document.querySelector('.addDatasetNameList'), editType, datasetNameList[0]);
            }
            if (count === datasetNameList.length) {
              initFeature();
            }
          });
          });
        });
      }

      function createOptions(list, selectElement, selectType, selectDataset) {
        selectElement.innerHTML = '';
        list.forEach(function(item, index) {
          var option = document.createElement('option');
          option.value = item;
          option.innerText = item;
          getField(item);
          if (item === selectDataset) {
            option.selected = true;
            setTimeout(function() {
              renderAttribute(item);
            }, 1000);
          }
          selectElement.appendChild(option);
        });
      }

      function getField(datasetName) {
        new mapboxgl.supermap.FieldService(dataUrl).getFields(
          new mapboxgl.supermap.FieldParameters({
            datasource: dataSourceName,
            dataset: datasetName
          }),
          function (result) {
            if (!result.result) {
              return;
            }
            fieldList = result.result.fieldNames;
            fieldList.forEach(function(fieldName) {
              var xhr = new XMLHttpRequest();
              xhr.open('GET', dataUrl + '/datasources/' + dataSourceName + '/datasets/' + datasetName + '/fields/' + fieldName + '.json', true);
              xhr.onreadystatechange = function() {
                if (xhr.readyState === 4 && xhr.status === 200) {
                  var res = JSON.parse(xhr.responseText);
                  filterFields[datasetName][res.fieldInfo.name.toUpperCase()] = res.fieldInfo.isSystemField;
                }
              };
              xhr.send();
            });
          }
        );
      }

      function renderAttribute(datasetName, status) {
        var attributeElement = document.querySelector('.' + (status || 'add') + '-attribute-info');
        attributeElement.innerHTML = '';
        Object.keys(filterFields[datasetName]).forEach(function(key) {
          if (!filterFields[datasetName][key]) {
            var item = document.createElement('div');
            item.style.position = 'relative';
            item.className = key;
            var title = document.createElement('h6');
            title.innerText = key;
            item.appendChild(title);
            if (domainRules[key] && domainRules[key].type === 'CODE') {
                var selectValues = domainRules[key].codeInfos.map(function(item) {
                  return item.value;
                });
                var select = createSelect(selectValues);
                item.appendChild(select);
              return;
            }
            
            var inputEle = document.createElement('input');
            inputEle.className = 'input-element';
            inputEle.label = key;
            inputEle.value = '';
            item.appendChild(inputEle);
            attributeElement.appendChild(item);
          }
        });
      }

      function createSelect(list) {
        var select = document.createElement('select');
        select.className = 'select-element';
        list.forEach(function(item) {
          var option = document.createElement('option');
          option.value = item;
          option.innerText = item;
          select.appendChild(option);
        });
        return select;
      }

      function renderEditAttribute(status, properties) {
        var attributeElement = document.querySelector('.' + (status || 'edit') + '-attribute-info');
        attributeElement.innerHTML = '';
        Object.keys(properties).forEach(function(key) {
          if (key === 'datasetName') {
            return;
          }
          var item = document.createElement('div');
          item.style.position = 'relative';
          item.className = key;
          var title = document.createElement('h6');
          title.innerText = key;
          item.appendChild(title);
          if (domainRules[key] && domainRules[key].type === 'CODE') {
                var selectValues = domainRules[key].codeInfos.map(function(item) {
                  return item.value;
                });
                var select = createSelect(selectValues);
                item.appendChild(select);
              return;
            }
          var inputEle = document.createElement('input');
          inputEle.className = 'input-element';
          inputEle.disabled = filterFields[currentFeature.dataset][key];
          inputEle.value = properties[key];
          inputEle.label = key;
          item.appendChild(inputEle);
          if (key === 'VIDEO' && properties[key]) {
            var videoPlayIcon = document.createElement('div');
            videoPlayIcon.className = 'playIcon';
            var video = document.createElement('video');
            video.src = properties[key];
            video.className = "video-element";
            item.appendChild(videoPlayIcon);
            item.appendChild(video);
            previewVideo(video);
          } else if (key === 'IMG') {
            var img = document.createElement('img');
            img.src = properties[key];
            img.className = "img-element";
            new Viewer(img);
            item.appendChild(img);
          }
          attributeElement.appendChild(item);
        });
      }

      function previewVideo(ele) { 
        var modal = document.querySelector('.video-modal');
        var video1 = document.querySelector('.video-modal video');
        ele.addEventListener('click', function onOpen() {
          modal.style.display = 'flex';
          video1.src = ele.src;
          video1.play();
        });
        
        modal.addEventListener('click', function onClose() {
          modal.style.display = 'none';
          video1.pause();
        });
      }

      function bindEvents() {
        document.querySelector('.addDatasetNameList').addEventListener('change', function(e) {
          var value = e.target.value;
          currentFeature.dataset = value;
          currentDataset = value;
          var type = datasetInfoList[currentDataset].type;
          var source = datasetInfoList[currentDataset].source;
          currentFeature.type = type;
          createOptions(datasetNameList, document.querySelector('.addDatasetNameList'), type, value);
          startDraw(type, source);
        });

         // 切换状态
         document.querySelector('#addFeature').addEventListener('click', function() {
          if (isChanged) {
            var message = document.querySelector('.message');
            message.style.display = 'block';
            setTimeout(() => {
              message.style.display = 'none';
            }, 3000);
            document.querySelector('.add-tips').style.display = 'inline-block';
            return;
          }
          switchPanel('add');
        });
        document.querySelector('#editFeature').addEventListener('click', function() {
          if (isChanged) {
            var message = document.querySelector('.message');
            message.style.display = 'block';
            setTimeout(() => {
              message.style.display = 'none';
            }, 3000);
            document.querySelector('.add-tips').style.display = 'inline-block';
            return;
          }
          switchPanel('edit');
        });
        document.querySelector('#deleteFeature').addEventListener('click', function() {
          if (isChanged) {
            var message = document.querySelector('.message');
            message.style.display = 'block';
            setTimeout(() => {
              message.style.display = 'none';
            }, 3000);
            document.querySelector('.add-tips').style.display = 'inline-block';
            return;
          }
          switchPanel('delete');
        });

        document.querySelector('.add-attribute-info').addEventListener('change', checkInput);
        document.querySelector('.edit-attribute-info').addEventListener('change', checkInput);

        content.addEventListener('change', function(e) {
          var x;
          var y;
          if (e.target.className.indexOf('coordX') > -1) {
            x = e.target.value;
            y = document.querySelector('.coordY').value;
          } else if (e.target.className.indexOf('coordY') > -1) {
            y = e.target.value;
            x = document.querySelector('.coordX').value;
          }
          draw.appendCoordinates([[x, y]]);
          overlayPopup.setPosition([x, y]);
        });

        document.querySelector('.cancel-add').addEventListener('click', function() {
          if (addFeatureId) {
            draw.delete(addFeatureId);
            currentFeature.data = null;
            if (currentShowPanel) {
              document.querySelector('.' + currentShowPanel).style.display = 'none';
            }
            document.querySelector('.message').style.display = 'none';
            document.querySelector('.add-tips').style.display = 'none';
            isChanged = false;
          }
        });

        document.querySelector('.cancel-edit').addEventListener('click', function() {
          if (currentShowPanel) {
              document.querySelector('.' + currentShowPanel).style.display = 'none';
          }
          if (curEditOriginFeatures.length) {
            curEditOriginFeatures.forEach(function(feature) {
              map.setFilter(feature.properties.datasetName, null);
              draw.delete(feature.id);
            });
            curEditOriginFeatures = [];
            document.querySelector('.message').style.display = 'none';
            document.querySelector('.add-tips').style.display = 'none';
            isChanged = false;
            status = '';
            endDraw();
          }
        });

        document.querySelector('.cancel-delete').addEventListener('click', function() {
          var deleteEle = document.querySelector('.delete-feature-list');
          deleteEle.innerHTML = '';
          deleteList = [];
          if (currentShowPanel) {
            document.querySelector('.' + currentShowPanel).style.display = 'none';
          }
        });
      }

      function switchPanel(className, fromAdd) {
        if (currentShowPanel) {
          document.querySelector('.' + currentShowPanel).style.display = 'none';
        }
        var type = datasetInfoList[currentDataset].type;
        var source = datasetInfoList[currentDataset].source;
        if (className === 'add') {
          document.querySelector('.edit-tips').style.display = 'none';
          startDraw(type, source);
          document.querySelector('.add-feature-info').style.display = 'block';
          currentShowPanel = 'add-feature-info';
          status = 'ADD';
        } else if (className === 'edit') {
          draw.changeMode('simple_select');
          if (fromAdd) {
            fillContent();
            document.querySelector('.edit-feature-info').style.display = 'block';
          } else {
            document.querySelector('.edit-tips').style.display = 'block';
          }
          currentShowPanel = 'edit-feature-info';
          status = 'EDIT';
          startSelect(source);
        } else if (className === 'delete') {
          document.querySelector('.edit-tips').style.display = 'none';
          endDraw();
          document.querySelector('.delete-feature-info').style.display = 'block';
          currentShowPanel = 'delete-feature-info';
          status = 'DELETE';
          startSelect(source);
        }
      }

      function fillContent() {
        if (currentFeature) {
          document.querySelector('.edit-dataset').innerText = currentFeature.dataset;
          document.querySelector('.edit-feature-info>.space-info>.input-element').value = JSON.stringify({ geometry: currentFeature.data.geometry});
          renderEditAttribute('edit', currentFeature.data.properties);
        }
      }

      var saveBtn = document.querySelector('.addSave');
      var editBtn = document.querySelector('.editSave');
      saveBtn.addEventListener('click', function () {
        document.querySelector('.message').style.display = 'none';
        document.querySelector('.add-tips').style.display = 'none';
        isChanged = false;
        save('add');
      });
      editBtn.addEventListener('click', function () {
        document.querySelector('.message').style.display = 'none';
        document.querySelector('.add-tips').style.display = 'none';
        isChanged = false;
        save('edit');
      });
      var deleteBtn = document.querySelector('.delete');
      deleteBtn.addEventListener('click', function () {
        document.querySelector('.delete-modal').style.display = 'block';
      });
      var deleteModalBtn = document.querySelector('.final-delete');
      deleteModalBtn.addEventListener('click', function () {
        document.querySelector('.delete-modal').style.display = 'none';
        deleteFeature();
      });
      var deleteBtnCancel = document.querySelector('.final-delete-cancel');
      deleteBtnCancel.addEventListener('click', function () {
        document.querySelector('.delete-modal').style.display = 'none';
      });
      function save(type) {
        var properties = {};
        var attributeElement = document.querySelector('.' + type + '-attribute-info');
        var listArr = Array.prototype.slice.call(attributeElement.children);
        listArr.forEach(function(item, index) {
          var itemArr = Array.prototype.slice.call(item.children);
          properties[itemArr[0].textContent] = itemArr[1].value;
        });
        currentFeature.data.properties = properties;
        if (!currentFeature.data.id) {
          datasetInfoList[currentDataset].uniqueId++;
          currentFeature.data.id = datasetInfoList[currentDataset].uniqueId;
        };
        isUpadate = type !== 'add';
        if (!currentFeature.data.properties['SMUSERID']) {
          currentFeature.data.properties['SMUSERID'] = currentFeature.data.id;
        }
        if (type === 'edit') {
          var allFeature = draw.getAll();
          var datas = map.getSource(currentDataset)._data;
          datas.features.forEach(function(feature) {
            allFeature.features.forEach(function(editFeature) {
              if (feature.id === editFeature.id) {
                feature = editFeature;
              };
            });
          });
        };

        
        
        commit(isUpdate);
        switchPanel('edit', true);
      }
      

      function initFeature() {
        // 按照面 线 点的顺序渲染
        var featureService = new mapboxgl.supermap.FeatureService(dataUrl);
        var datasetOrder = [].concat(datasetTypeClassify['Fill'], datasetTypeClassify['Line'], datasetTypeClassify['Point'])
        // var datasetOrder = [].concat(datasetTypeClassify['Point'])
        // var datasetOrder = ['China_island', 'demo_line', 'Capitals'];
        datasetOrder.forEach(function(datasetName) {
          var getFeatureParams = new mapboxgl.supermap.GetFeaturesBySQLParameters({
            queryParameter: {
              name: datasetName + "@" + dataSourceName,
              attributeFilter: 'SMID < 1000'
            },
            toIndex: -1,
            datasetNames: [dataSourceName + ":" + datasetName]
          });

          featureService.getFeaturesBySQL(getFeatureParams, function (serviceResult) {
            var geojsonFeatures = serviceResult.result.features;
            geojsonFeatures.features.forEach(function(feature) {
              feature.properties.datasetName = datasetName;
            });
              geojsonFeatures.features.forEach(function(feature) {
                if (feature.id > datasetInfoList[datasetName].id) {
                  datasetInfoList[datasetName].id = feature.id;
                }
              });
              if (geojsonFeatures.features[0]) {
               addVectorLayer(geojsonFeatures.features[0].geometry.type, geojsonFeatures, datasetName);
              }
              return;
            });
        });
      }

      function commit(isUpdate) {
        if (currentFeature.data) {
          var addFeatureParams = new mapboxgl.supermap.EditFeaturesParameters({
            features: currentFeature.data,
            dataSourceName: dataSourceName,
            dataSetName: currentDataset,
            editType: status === 'EDIT' ? 'update' : 'add',
            returnContent: true
          });
          editFeaturesService.editFeatures(addFeatureParams, function (serviceResult) {
            if (serviceResult.result.succeed) {
              if(addFeatureId) {
                draw.delete(addFeatureId);
                var addFeature = _.cloneDeep(currentFeature.data);
                addFeature.properties.datasetName = currentDataset;
                var source = map.getSource(currentDataset);
                var features = source._data.features;
                features.push(addFeature);
                source.setData({
                  type: 'FeatureCollection',
                  features: features
                });
              }
              widgets.alert.showAlert(isUpdate ? resources.text_updateFeaturesSuccess : resources.text_addFeaturesSuccess, true);
            }
          });
        }
      }

      function deleteFeature() {
        Object.keys(deleteList).forEach(function(dataset) {
          var addFeatureParams = new mapboxgl.supermap.EditFeaturesParameters({
            dataSourceName: dataSourceName,
            dataSetName: dataset,
            IDs: deleteList[dataset],
            editType: 'delete'
          });
          editFeaturesService.editFeatures(addFeatureParams, function (serviceResult) {
            if (serviceResult.result.succeed) {
              var source = map.getSource(dataset);
              var data = source._data;
              deleteList[dataset].forEach((deleteId) => {
                var idx = data.features.findIndex((feature) => {
                  return feature.id === deleteId;
                });
                data.features.splice(idx, 1);
              });
              source.setData(data);
              var deleteEle = document.querySelector('.delete-feature-list');
              deleteEle.innerHTML = '';
              deleteList = [];
              widgets.alert.showAlert(resources.text_deleteSuccess, true);
            }
          });
        });
      }
      function startSelect(source) {
        clearInteraction();
        map.on('click', function (e) {
          var res = map.queryRenderedFeatures(e.point);
          if (!res[0]) {
            return;
          }
          if (status === 'EDIT') {
            if (res[0] && ['mapbox-gl-draw-cold', 'mapbox-gl-draw-hot'].indexOf(res[0].source) === -1) {
              if (preSelectId) {
              draw.delete(preSelectId);
              curEditOriginFeatures.forEach((feature, idx) => {
                if (preSelectId === feature.id) {
                  curEditOriginFeatures.splice(idx, 1);
                }
              });
            }
            isChanged = true;
              var source = map.getSource(res[0].source);
              var type = res[0].type;
              var targetFeature = source._data.features.find(function(feature) {
                return feature.id === res[0].id;
              });
              var geometry = targetFeature.geometry;
              var id = res[0].id;
              var properties = res[0].properties;
              var editFeature = {
                type: type,
                geometry: geometry,
                id: id,
                properties: properties
              };
              var layer = map.getLayer(properties.datasetName || properties['user_datasetName']);
              if (!layer) {
                return;
              }
              var allIds = source._data.features.map(function(feature) {
                return feature.id;
              });
              allIds = allIds.filter(function(id) {
                if (id !== +properties.SMID && !curEditOriginFeatures.find(function(feature) {
                  return feature.id === id;
                })) {
                  return true;
                }
                return false;
              });
              allIds = allIds.map(function(id) {
                return id + '';
              });
              preSelectId = draw.add(editFeature)[0];
              var filters = ['match', ['get', 'SMID'], allIds, true, false];
              map.setFilter(properties.datasetName, filters);
              draw.changeMode(geometry.type === 'Point' ? 'simple_select' : 'direct_select', { featureId: id });
              document.querySelector('.edit-tips').style.display = 'none';
              currentFeature.dataset = editFeature.properties.datasetName;
              document.querySelector('.edit-dataset').innerText = currentFeature.dataset;
              currentDataset = currentFeature.dataset;
              currentFeature.data = editFeature;
              curEditOriginFeatures.push(editFeature);
              document.querySelector('.edit-feature-info').style.display = 'block';
              document.querySelector('.edit-feature-info>.space-info>.input-element').value = JSON.stringify({ geometry: currentFeature.data.geometry });
              renderEditAttribute('edit', currentFeature.data.properties);
            }
          } else if (status == 'DELETE') {
            var feature = res[0];
            if (feature) {
            var datasetName = feature.properties.datasetName;
            var id = feature.id;
            if (['mapbox-gl-draw-cold', 'mapbox-gl-draw-hot'].indexOf(feature.source) > -1) {
              datasetName = feature.properties['user_datasetName'];
              id = feature.properties['user_id'];
            }
            if (!deleteList[datasetName]) {
              deleteList[datasetName] = []
            }
            if (deleteList[datasetName].indexOf(id) > -1) {
              return;
            }
            deleteList[datasetName].push(id);
            var deleteItem = document.createElement('div');
            deleteItem.innerText = 'SMID: ' + id + ' (' + datasetName + ')';
            var deleteEle = document.querySelector('.delete-feature-list');
            deleteEle.appendChild(deleteItem);
            }
          }
        });
        map.on('draw.update', function (e) {
          var feature = e.features[0];
          if (status === 'EDIT') {
              document.querySelector('.edit-tips').style.display = 'none';
              currentFeature.dataset = feature.properties.datasetName;
              currentFeature.data = feature;
              document.querySelector('.edit-feature-info').style.display = 'block';
              document.querySelector('.edit-feature-info>.space-info>.input-element').value = JSON.stringify({ geometry: currentFeature.data.geometry});
              renderEditAttribute('edit', currentFeature.data.properties);
              updateChanged = true;
              document.querySelector('.editSave').disabled = false;
          }
        });
        map.on('draw.selectionchange', function() {
          updateChanged = true;
          document.querySelector('.editSave').disabled = false;
        });
      }

      function startDraw(type, source) {
        endDraw();
        var popup = new mapboxgl.Popup({ className: 'popup' })
        .setDOMContent(container)
        .setMaxWidth("300px")
        .addTo(map);
        map.on('mousemove', function (evt) {
          var coordinate = evt.lngLat;
          popup.setLngLat(coordinate);
          content.querySelector('.coordX').value = coordinate.lng;
          content.querySelector('.coordY').value = coordinate.lat;
        });
        var drawTypeMap = {
          REGION: 'draw_polygon',
          LINE: 'draw_line_string',
          POINT: 'draw_point'
        }
        draw.changeMode(drawTypeMap[type]);
      }

      function endDraw() {
      }

      function clearInteraction() {
      }

    </script>
  </body>
</html>
